package com.UKIT.airtickets.Service.Handlers

import android.content.Context
import android.widget.Toast
import androidx.room.Room
import com.UKIT.airtickets.DB.AppDatabase
import com.UKIT.airtickets.DB.UserSettings
import com.UKIT.airtickets.Service.SettingsApp
import com.UKIT.airtickets.Service.ValidationUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class SettingsHandler(private val context: Context) {

    private val coroutineScope = CoroutineScope(Dispatchers.IO)

    fun changePassword(oldPassword: String, newPassword: String) {
        if(!ValidationUtils.checkPasswordTrue(newPassword)){
            Toast.makeText(context, "Данные заполнены неверно", Toast.LENGTH_SHORT).show()
        }
        coroutineScope.launch {
            val db = Room.databaseBuilder(context, AppDatabase::class.java, "airtickets.db")
                .fallbackToDestructiveMigration()
                .build()

            if (db.userDao().updatePassword(SettingsApp.userId.toLong(), oldPassword, newPassword) > 0) {
                launch(Dispatchers.Main) {
                    Toast.makeText(context, "Пароль успешно изменен", Toast.LENGTH_SHORT).show()
                }
            } else {
                launch(Dispatchers.Main) {
                    Toast.makeText(context, "Данные заполнены неверно", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    fun changeLanguage(language: String) {
        coroutineScope.launch {
            val db = Room.databaseBuilder(context, AppDatabase::class.java, "airtickets.db")
                .fallbackToDestructiveMigration()
                .build()

            db.userSettingsDao().updateUserSettings(
                UserSettings(
                    SettingsApp.userId.toLong(),
                    db.userSettingsDao().getUserSettings(SettingsApp.userId.toLong())!!.isNight,
                    language,
                    db.userSettingsDao().getUserSettings(SettingsApp.userId.toLong())!!.notification,
                )
            )
        }
    }
}
